package com.design.prototype.demo3;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

// Car 类作为原型类
public class Car implements Cloneable,Serializable {
    private String make;
    private String model;
    private int year;
    private List<String> features;

    public Car(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
        this.features = new ArrayList<>();
    }

    public String getMake() {
        return make;
    }

    public String getModel() {
        return model;
    }

    public int getYear() {
        return year;
    }

    public void addFeature(String feature) {
        features.add(feature);
    }

    public void removeFeature(String feature) {
        features.remove(feature);
    }

    public void printFeatures() {
        System.out.println("Car Features:");
        for (String feature : features) {
            System.out.println("- " + feature);
        }
    }

    // 深拷贝克隆方法
    @Override
    public Object clone() throws CloneNotSupportedException {
        ByteArrayOutputStream outputStream = null;
        ObjectOutputStream objectOutputStream = null;
        ByteArrayInputStream inputStream = null;
        ObjectInputStream objectInputStream = null;

        try {
            // 将对象写入输出流
            outputStream = new ByteArrayOutputStream();
            objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(this);

            // 从输出流中读取对象并返回
            inputStream = new ByteArrayInputStream(outputStream.toByteArray());
            objectInputStream = new ObjectInputStream(inputStream);
            return objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (objectOutputStream != null) {
                    objectOutputStream.close();
                }
                if (objectInputStream != null) {
                    objectInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
